package com.leyou.gateway.filter;

import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.pojo.UserInfo;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.constant.LyConstants;
import com.leyou.gateway.config.FilterProperties;
import com.leyou.gateway.config.JwtProperties;
import com.leyou.gateway.job.TokenHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    private JwtProperties jwtProp;

    @Autowired
    private FilterProperties filterProp;

    @Autowired
    private TokenHolder tokenHolder;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取当前请求的request和response
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //给当前网关要转发的request添加请求头信息
        request.mutate().header(LyConstants.SERVER_AUTH_HEADER_KEY, tokenHolder.getToken()).build();
        //获取当前请求的路径
        String path = request.getPath().toString();
        //判断当前路径是否在白名单
        if(isWhite(path)){
            //继续执行其他过滤器链
            return chain.filter(exchange);
        }
        //获取cookie
        String token = request.getCookies().getFirst(jwtProp.getCookie().getCookieName()).getValue();
        //解析token
        Payload<UserInfo> payload = null;
        try {
            payload = JwtUtils.getInfoFromToken(token, jwtProp.getPublicKey(), UserInfo.class);
        }catch (Exception e){
            //如果出现异常，表示没有登录，则不允许继续访问服务器
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //获取用户id
        Long userId = payload.getUserInfo().getId();
        //把用户id放入请求头中传递下去
        request.mutate().header(LyConstants.AUTH_USER_ID_HEADER_KEY, userId.toString()).build();
        //继续执行其他过滤器链
        return chain.filter(exchange);
    }

    //校验当前请求地址是否在白名单中
    private Boolean isWhite(String path) {
        //获取白名单
        List<String> allowPaths = filterProp.getAllowPaths();
        for (String allowPath : allowPaths) {
            if(path.contains(allowPath)){
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
